package com.example.demo.config;

import com.example.demo.model.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {       //统一结果适配器
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        //false  不处理
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        ObjectMapper objectMapper=new ObjectMapper();
        if(body instanceof String){
            return objectMapper.writeValueAsString(Result.success(body));    //如果body的数据为String 会报错
            //所以使用这个方法会将数据转换成"{\"code\":200,\"message\":\"success\",\"data\":\"查询成功\"}"  然后前端会进行转换
        }
        if(body instanceof Result){    //如果不执行这段代码 就会重复套上result格式
            return body;
        }
        return Result.success(body);    //返回Result对象
    }
}
